﻿namespace Pp.UI.Controllers
{
    using System;
    using System.Web.Mvc;
    using Core;
    using Core.Extentions;
    using Dto;
    using Globalization;
    using Models;

    public class AccountController : BaseController
    {
        public ActionResult LogOn()
        {
            ViewData["Title"] = Res.Title_MainPage;
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            ViewData["Title"] = Res.Title_MainPage;
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    model.UserName = model.UserName.ToSeo();
                    var user = UserRepository.GetByUserName(model.UserName);
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    return Url.IsLocalUrl(returnUrl)
                               ? (ActionResult)Redirect(returnUrl)
                               : RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", Res.Message_User_NoFound);
            }
            return View(model);
        }


        public ActionResult Register()
        {
            ViewData["Title"] = Res.Label_Register;
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            ViewData["Title"] = Res.Label_Register;
            if (!model.UserName.CheckSeo())
                ModelState.AddModelError("UserName", Res.Message_Character);
            if (ModelState.IsValid)
            {

                model.UserName = model.UserName.ToSeo();
                var createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus.Success)
                {
                    FormsService.SignIn(model.UserName, true);
                    return RedirectToAction("Update", "Account");
                }
                ModelState.AddModelError("", createStatus.Error);
            }
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }



        [Authorize]
        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }
        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["Title"] = Res.Label_PasswordEdit;
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            ViewData["Title"] = Res.Label_PasswordEdit;
            if (ModelState.IsValid)
            {
                var result = MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                if (result.Success)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                ModelState.AddModelError("", result.Error);
            }
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }
        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {
            ViewData["Title"] = Res.Information_PasswordEdit_successful;
            return View();
        }

        [Authorize]
        public ActionResult List(int? page)
        {
            ViewData["Title"] = Res.Label_Member_List;
            var users = UserRepository.GetUsers(page, 21);
            var userDto = UserRepository.GetByUserName(User.Identity.Name);
            return View(new AccountListViewModel
                            {
                                Users = users,
                                UserSmallDto = userDto
                            });
        }
        [Authorize]
        public ActionResult Update()
        {
            ViewData["Title"] = Res.Label_ProfileEdit;
            var user = UserRepository.GetByUsername<UserEditDto>(User.Identity.Name);
            if (user == null) throw new Exception(Res.Information_Object_NoFound);
            return View(user);
        }
        [Authorize, HttpPost, ValidateInput(false)]
        public ActionResult Update(UserEditViewModel userEditDto)
        {
            ViewData["Title"] = Res.Label_ProfileEdit;
            if (!userEditDto.Username.CheckSeo())
            {
                ModelState.AddModelError("UserName", Res.Message_Character);
            }
            if (ModelState.IsValid)
            {
                userEditDto.Username = userEditDto.Username.ToSeo();
                userEditDto.CvInfo = Server.HtmlEncode(userEditDto.CvInfo);

                var result = UserRepository.UpdateProfile(userEditDto, User.Identity.Name);
                if (result.Success)
                {
                    Flash(Res.Information_Profile_Update_Successful, MessageType.Success);
                    return RedirectToAction("Update");
                }
                ModelState.AddModelError("", result.Error);
            }
            return View(userEditDto);
        }

        [HttpPost]
        public JsonResult IsExists(string username)
        {
            if (!username.CheckSeo()) return Json(Result.AsError(Res.Information_special_character));
            return username.Length < 5
                       ? Json(Result.AsError(Res.Error_username_minsize))
                       : Json(!UserRepository.IsExists(username, User.Identity.Name)
                                  ? Result.AsSuccess()
                                  : Result.AsError(Res.Information_User_allready_exsist));
        }
    }
}
